package injection;

import domain.User;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author jackcfan
 * @date 2021/9/15
 */
@Configuration
public class ApiSetterInjectionTest {

    @Test
    public void test(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册 Configuration class 配置类
        applicationContext.register(this.getClass());

        // 通过 API 注册 UserHolder
        applicationContext.registerBeanDefinition("userHolder", createUserHoldBeanDefinition());

        // 启动 Spring 上下文
        applicationContext.refresh();

        User user = applicationContext.getBean(User.class);
        System.out.println("user:"+user);

        UserHolder userHolder = applicationContext.getBean(UserHolder.class);
        System.out.println("userHolder:"+userHolder);

        applicationContext.close();
    }

    // 通过 API 设置 userHold 的依赖
    // 类似 xml 配置 ：<property name="user" ref="apiUser"/>
    // beanDefinitionBuilder.addPropertyReference
    private BeanDefinition createUserHoldBeanDefinition(){
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(UserHolder.class);
        beanDefinitionBuilder.addPropertyReference("user", "apiUser");
        return beanDefinitionBuilder.getBeanDefinition();
    }

    @Bean
    public User apiUser(){
        User user = new User();
        user.setId(1L);
        user.setName("api user");
        return user;
    }
}
